<?php
namespace Tyrone\Model\Game;
use Tyrone\Model\Base;
use Medoo\Medoo;

class LogAsset extends Base
{
    protected $table = 'log_assets';
    protected  $item_id = 0;
    protected $uniqueKey = ['platform','server_id','day','role_id','type','origin'];
    public function setUniqueKey($uniqueKey){
        $this->uniqueKey = $uniqueKey;
    }

    public function getAssetList($limit,$maxId){
        return $this->database->select($this->table.'(le)',[
            '[>]role(r)' => ['le.role_id'=>'r.id']
        ],[
            'le.*',
            'day' => Medoo::raw('FROM_UNIXTIME(time,\'%Y%d%m\')'),
            'r.platform',
            'r.server_id',
        ],[
            'item_id'=>$this->item_id,
            "le.id[>]" => $maxId,
            "LIMIT" => $limit,
            "ORDER" => ["id" => "ASC"],
        ]);
    }

    public function sync($mysql,$platform,$plat_server,$table,$num_field){
        $limit = 10000;
        $maxIdModel = new \Tyrone\Model\TableMaxId($mysql);
        $maxIdModel = $maxIdModel->setSid($platform,$plat_server);
        $maxId = $maxIdModel->getMaxId($table) ?: 0;

        $list =  $this->getAssetList($limit,$maxId);

        $statData = [];
        foreach ($list as $row) {
            $maxId = max($maxId,$row['id']);
            $uniqueData = array_intersect_key(array_flip($this->uniqueKey),$row);
            $key = implode('_',array_values($uniqueData));
            if (isset($statData[$key])) {
                $statData[$key][$num_field] += $row[$num_field];
            } else {
                $statData[$key] = $row;
                $statData[$key]['id'] = $key;

                $statData[$key][$num_field] = $row[$num_field];
            }

        }
        $maxIdModel->database->batchUpdateOrInsert($table,array_values($statData),['id']);

        $maxIdModel->updateMaxId("stat_gold", $maxId);
        return compact('maxId')  + ['count'=>count($statData)];
    }


    /**
     * 资源item_id的统计
     * @param $item_id
     * @return array
     */
    public function statGoldStore($item_id)
    {
        return $this->database->select($this->table.'(re)',[
            '[><]role(r)' => ['re.role_id' => 'id']
        ],[
            'r.platform',
            'gold' => Medoo::raw('SUM(re.item_id)')
        ],[
            'item_id' => $item_id,
            'GROUP' => 'r.platform'
        ]);
    }

}